#    Copyright 2014 COOPGIS Consulting
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os







#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopgis/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject.settings")

import djangoproject.settings
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.sites.models import Site

#import COOPGIS_Ajax, COOPGIS_DynamicTemplate, COOPGIS_FormMisc, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
#import COOPGIS_ReportLabStakerReport
from django.db import transaction, connections



def DeleteExisting():
    print "Deleting Assemblies:  " + str(Assembly.objects.all().count())
    Assembly.objects.all().delete()

    print "Deleting Sites:  " + str(Site.objects.all().count())
    Site.objects.all().delete()
    print "Deleting Compatible Units:  " + str(CompatibleUnit.objects.all().count())
    CompatibleUnit.objects.all().delete()
    print "Deleting Spans:  " + str(Span.objects.all().count())
    Span.objects.all().delete()
    print "Deleting Stations:  " + str(Station.objects.all().count())
    Station.objects.all().delete()
    print "Deleting Install Statuses:  " + str(InstallStatus.objects.all().count())
    InstallStatus.objects.all().delete()
    print "Deleting COOPGISConfig:  " + str(COOPGISConfig.objects.all().count())
    COOPGISConfig.objects.all().delete()
    print "Deleting Map Files:  " + str(Map.objects.all().count())
    Map.objects.all().delete()
    print "Deleting Map Templates:  " + str(MapTemplate.objects.all().count())
    MapTemplate.objects.all().delete()
    print "Deleting Symbology"
    SymbologyProtectedSpan.objects.all().delete()
    SymbologyCutOut.objects.all().delete()
    SymbologyFeeder.objects.all().delete()
    SymbologyPoleJointUse.objects.all().delete()
    SymbologyPoleTreatment.objects.all().delete()
    SymbologyLight.objects.all().delete()
    SymbologyMeter.objects.all().delete()
    SymbologyOpenPoint.objects.all().delete()
    SymbologyPrimaryLine.objects.all().delete()
    SymbologySecondaryLine.objects.all().delete()
    SymbologyStakerWorkOrderStation.objects.all().delete()
    SymbologyStakerWorkOrderSpan.objects.all().delete()
    SymbologyTransformer.objects.all().delete()
    SymbologyPole.objects.all().delete()
    SymbologyNonProtectingAssembly.objects.all().delete()
    SymbologyRecloser.objects.all().delete()
    SymbologyRegulator.objects.all().delete()
    SymbologySpanGuy.objects.all().delete()
    SymbologySubstation.objects.all().delete()
    SymbologySwitch.objects.all().delete()
    SymbologyURDMarker.objects.all().delete()
    SymbologyVault.objects.all().delete()
    SymbologyRadioLink.objects.all().delete()
    SymbologyRadioStation.objects.all().delete()



def ResetSequences():
    #output of the command python manage.oy sqlsequencereset djangoproject
    print "Reseting Database Sequences"
    c = connections['default'].cursor()
    try:
        c.execute("""SELECT setval(pg_get_serial_sequence('"coopgisconductorplacement"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisconductorplacement";
                     SELECT setval(pg_get_serial_sequence('"coopgisstakerworkorder"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisstakerworkorder";
                     SELECT setval(pg_get_serial_sequence('"coopgisinstallstatus"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisinstallstatus";
                     SELECT setval(pg_get_serial_sequence('"coopgisstakerassemblyhistory"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisstakerassemblyhistory";
                     SELECT setval(pg_get_serial_sequence('"coopgisstakerrecipe"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisstakerrecipe";
                     SELECT setval(pg_get_serial_sequence('"coopgisstakerquickgeneratepolygon"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisstakerquickgeneratepolygon";
                     SELECT setval(pg_get_serial_sequence('"coopgisomscustomer"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisomscustomer";
                     SELECT setval(pg_get_serial_sequence('"coopgisomssubstationmap"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisomssubstationmap";
                     SELECT setval(pg_get_serial_sequence('"coopgisomscircuitmap"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisomscircuitmap";
                     SELECT setval(pg_get_serial_sequence('"coopgisstation"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisstation";
                     SELECT setval(pg_get_serial_sequence('"coopgisspan"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisspan";
                     SELECT setval(pg_get_serial_sequence('"coopgisstate"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisstate";
                     SELECT setval(pg_get_serial_sequence('"coopgiscounty"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscounty";
                     SELECT setval(pg_get_serial_sequence('"coopgiswater"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiswater";
                     SELECT setval(pg_get_serial_sequence('"coopgiszipcode"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiszipcode";

                     SELECT setval(pg_get_serial_sequence('"coopgisgrid"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisgrid";
                     SELECT setval(pg_get_serial_sequence('"coopgiscity"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscity";
                     SELECT setval(pg_get_serial_sequence('"coopgisboarddistrict"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisboarddistrict";
                     SELECT setval(pg_get_serial_sequence('"countyparcellexington"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "countyparcellexington";
                     SELECT setval(pg_get_serial_sequence('"coopgisboarddistrictpoint"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisboarddistrictpoint";
                     SELECT setval(pg_get_serial_sequence('"coopgisboarddistrictedge"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisboarddistrictedge";

                     SELECT setval(pg_get_serial_sequence('"coopgisreportpagenumberpolygon"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisreportpagenumberpolygon";
                     SELECT setval(pg_get_serial_sequence('"coopgisgpstrace"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisgpstrace";
                     SELECT setval(pg_get_serial_sequence('"coopgislandmarktype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislandmarktype";
                     SELECT setval(pg_get_serial_sequence('"coopgislandmarkpoint"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislandmarkpoint";
                     SELECT setval(pg_get_serial_sequence('"coopgislandmarkline"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislandmarkline";
                     SELECT setval(pg_get_serial_sequence('"coopgislandmarkpolygon"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislandmarkpolygon";
                     SELECT setval(pg_get_serial_sequence('"coopgispoletreatmenttype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispoletreatmenttype";
                     SELECT setval(pg_get_serial_sequence('"coopgispoletreatment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispoletreatment";
                     SELECT setval(pg_get_serial_sequence('"coopgispolejointusetype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispolejointusetype";
                     SELECT setval(pg_get_serial_sequence('"coopgispolejointuse"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispolejointuse";
                     SELECT setval(pg_get_serial_sequence('"coopgiscompany"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscompany";
                     SELECT setval(pg_get_serial_sequence('"coopgisassemblyowner"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisassemblyowner";
                     SELECT setval(pg_get_serial_sequence('"coopgismaterial"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgismaterial";
                     SELECT setval(pg_get_serial_sequence('"coopgisparteach"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisparteach";
                     SELECT setval(pg_get_serial_sequence('"coopgispart"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispart";
                     SELECT setval(pg_get_serial_sequence('"coopgispartsupplier"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispartsupplier";
                     SELECT setval(pg_get_serial_sequence('"coopgispartcost"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispartcost";
                     SELECT setval(pg_get_serial_sequence('"coopgisvoltage"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisvoltage";
                     SELECT setval(pg_get_serial_sequence('"coopgiscompatibleunitcategory"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscompatibleunitcategory";
                     SELECT setval(pg_get_serial_sequence('"coopgiscompatibleunit"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscompatibleunit";
                     SELECT setval(pg_get_serial_sequence('"coopgispartmap"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispartmap";
                     SELECT setval(pg_get_serial_sequence('"coopgislightlamptype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislightlamptype";
                     SELECT setval(pg_get_serial_sequence('"coopgislightfixturetype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislightfixturetype";
                     SELECT setval(pg_get_serial_sequence('"coopgistransformerwindingtype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgistransformerwindingtype";
                     SELECT setval(pg_get_serial_sequence('"coopgispolerightofwaystatus"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgispolerightofwaystatus";
                     SELECT setval(pg_get_serial_sequence('"coopgismeterservicetype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgismeterservicetype";
                     SELECT setval(pg_get_serial_sequence('"coopgisfuse"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisfuse";
                     SELECT setval(pg_get_serial_sequence('"coopgismeterform"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgismeterform";
                     SELECT setval(pg_get_serial_sequence('"coopgisassembly"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisassembly";
                     SELECT setval(pg_get_serial_sequence('"coopgisprotectingassembly"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisprotectingassembly";
                     SELECT setval(pg_get_serial_sequence('"coopgiscompatibleunitpricecontract"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscompatibleunitpricecontract";
                     SELECT setval(pg_get_serial_sequence('"coopgislightrate"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgislightrate";
                     SELECT setval(pg_get_serial_sequence('"coopgiscompatibleunitprice"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscompatibleunitprice";
                     SELECT setval(pg_get_serial_sequence('"warehousemeterinventorycheckin"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "warehousemeterinventorycheckin";
                     SELECT setval(pg_get_serial_sequence('"warehousemeterinspectionchoice"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "warehousemeterinspectionchoice";
                     SELECT setval(pg_get_serial_sequence('"coopgisgroundrodtest"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisgroundrodtest";
                     SELECT setval(pg_get_serial_sequence('"transformerbanktype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "transformerbanktype";
                     SELECT setval(pg_get_serial_sequence('"transformerbank"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "transformerbank";
                     SELECT setval(pg_get_serial_sequence('"coopgiscondition"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscondition";
                     SELECT setval(pg_get_serial_sequence('"coopgisconditionstatus"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisconditionstatus";
                     SELECT setval(pg_get_serial_sequence('"coopgisconditionmemberdescriptionhistory"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisconditionmemberdescriptionhistory";
                     SELECT setval(pg_get_serial_sequence('"coopgisyardlightassociatedwithmeternumber"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisyardlightassociatedwithmeternumber";
                     SELECT setval(pg_get_serial_sequence('"coopgisconditionassignment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisconditionassignment";
                     SELECT setval(pg_get_serial_sequence('"coopgisconditiondepartment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisconditiondepartment";
                     SELECT setval(pg_get_serial_sequence('"coopgisoutdoorlightconsumerownedlightcount"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisoutdoorlightconsumerownedlightcount";
                     SELECT setval(pg_get_serial_sequence('"coopgisoutdoorlightrate"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisoutdoorlightrate";
                     SELECT setval(pg_get_serial_sequence('"coopgisoutdoorlightproblemcode"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisoutdoorlightproblemcode";
                     SELECT setval(pg_get_serial_sequence('"coopamrgisphaseupdatelog"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopamrgisphaseupdatelog";
                     SELECT setval(pg_get_serial_sequence('"vegetationmanagerjob"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "vegetationmanagerjob";
                     SELECT setval(pg_get_serial_sequence('"vegetationmanagerjobstatus"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "vegetationmanagerjobstatus";
                     SELECT setval(pg_get_serial_sequence('"vegetationmanagercrew"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "vegetationmanagercrew";
                     SELECT setval(pg_get_serial_sequence('"vegetationmanagerjobspan"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "vegetationmanagerjobspan";
                     SELECT setval(pg_get_serial_sequence('"coopgiscommand"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscommand";
                     SELECT setval(pg_get_serial_sequence('"coopgiscistransactiontype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscistransactiontype";
                     SELECT setval(pg_get_serial_sequence('"coopgiscistransaction"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscistransaction";
                     SELECT setval(pg_get_serial_sequence('"coopgisciscompatibleunit"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisciscompatibleunit";
                     SELECT setval(pg_get_serial_sequence('"coopgiscurrentselection"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscurrentselection";
                     SELECT setval(pg_get_serial_sequence('"coopgisselectionpoint"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisselectionpoint";
                     SELECT setval(pg_get_serial_sequence('"coopgisselectionline"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisselectionline";
                     SELECT setval(pg_get_serial_sequence('"coopgiscircuittrace"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgiscircuittrace";
                     SELECT setval(pg_get_serial_sequence('"coopgisapplicationdefaultmap"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisapplicationdefaultmap";
                     SELECT setval(pg_get_serial_sequence('"coopgismap"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgismap";
                     SELECT setval(pg_get_serial_sequence('"coopgismaptemplate"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgismaptemplate";
                     SELECT setval(pg_get_serial_sequence('"coopgisconfig"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisconfig";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyprotectedspan"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyprotectedspan";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologycutout"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologycutout";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyfeeder"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyfeeder";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyjointuse"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyjointuse";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologypoletreatment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologypoletreatment";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologylight"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologylight";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologymeter"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologymeter";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyopenpoint"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyopenpoint";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyprimaryline"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyprimaryline";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologysecondaryline"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologysecondaryline";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologystakerworkorderstation"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologystakerworkorderstation";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologystakerworkorderspan"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologystakerworkorderspan";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologytransformer"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologytransformer";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologypole"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologypole";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologynonprotectingassembly"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologynonprotectingassembly";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyrecloser"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyrecloser";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyregulator"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyregulator";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyspanguy"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyspanguy";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologysubstation"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologysubstation";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyswitch"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyswitch";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyurdmarker"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyurdmarker";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyvault"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyvault";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyradiolink"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyradiolink";
                     SELECT setval(pg_get_serial_sequence('"coopgissymbologyradiostation"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgissymbologyradiostation";
                     SELECT setval(pg_get_serial_sequence('"substation"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substation";
                     SELECT setval(pg_get_serial_sequence('"substationequipmentsetting"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmentsetting";
                     SELECT setval(pg_get_serial_sequence('"substationequipmentsettingassignment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmentsettingassignment";
                     SELECT setval(pg_get_serial_sequence('"substationequipmentmodeltype"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmentmodeltype";
                     SELECT setval(pg_get_serial_sequence('"substationequipmentsubstationassignment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmentsubstationassignment";
                     SELECT setval(pg_get_serial_sequence('"substationcircuit"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationcircuit";
                     SELECT setval(pg_get_serial_sequence('"substationequipmentcircuitassignment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmentcircuitassignment";
                     SELECT setval(pg_get_serial_sequence('"substationequipmenttest"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmenttest";
                     SELECT setval(pg_get_serial_sequence('"substationequipment"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipment";
                     SELECT setval(pg_get_serial_sequence('"substationequipmentinspection"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmentinspection";
                     SELECT setval(pg_get_serial_sequence('"substationequipmenttemplate"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationequipmenttemplate";
                     SELECT setval(pg_get_serial_sequence('"substationinspection"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationinspection";
                     SELECT setval(pg_get_serial_sequence('"substationinspectionchoice"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "substationinspectionchoice";""")
    finally:
        c.close()


def LoadMapFiles():
    print "Loading Map Files"
    os.system("""echo "COPY coopgismaptemplate(id, "name", "tag", "username", "lastmodifydate", "createdate", "content") FROM '/opt/coopgis/scripts/Install/DefaultMapFiles/maptemplate.csv' DELIMITER ',' CSV;" | /usr/bin/psql coopgis""")
    os.system("""echo "COPY coopgismap(id, "name", "username", "lastmodifydate", "createdate", "content") FROM '/opt/coopgis/scripts/Install/DefaultMapFiles/map.csv' DELIMITER ',' CSV;" | /usr/bin/psql coopgis""")
    


def CreateInstallStatuses():
    print "Generating new InstallStatuses"
    New = InstallStatus()
    New.Name = 'Install'
    New.Description = 'Assemblies that are planned to be installed.'
    New.StarkerReportOrder = 1
    New.save()

    New = InstallStatus()
    New.Name = 'Existing'
    New.Description = 'Assemblies that exist in the field.'
    New.StarkerReportOrder = 2
    New.save()

    New = InstallStatus()
    New.Name = 'Remove'
    New.Description = 'Assemblies that are planned to be removed.'
    New.StarkerReportOrder = 3
    New.save()

#CreateInstallStatuses()

def CreateInitialCompatibleUnits():
    print "Generating new Compatible Units"
    New = CompatibleUnit.GetOrModify("7200 Transformer", StationIndicator=True, SubstationIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=False)
    New = CompatibleUnit.GetOrModify("Recloser", StationIndicator=True, RecloserIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=False)
    New = CompatibleUnit.GetOrModify("P50-3", StationIndicator=True, PoleIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerPoleIndicator=True, Height=50, Class=3)
    New = CompatibleUnit.GetOrModify("G25", StationIndicator=True, TransformerIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerTransformerIndicator=True)
    New = CompatibleUnit.GetOrModify("Meter", StationIndicator=True, MeterIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerMiscEquipmentIndicator=True)
    New = CompatibleUnit.GetOrModify("Light", StationIndicator=True, LightIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerMiscEquipmentIndicator=True)
    New = CompatibleUnit.GetOrModify("Substation Bus", SpanIndicator=True, ConductorIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerSpanAssemblyIndicator=True)
    New = CompatibleUnit.GetOrModify("4 ACSR", SpanIndicator=True, ConductorIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerSpanAssemblyIndicator=True)
    New = CompatibleUnit.GetOrModify("1/0 Triplex", SpanIndicator=True, ConductorIndicator=True, NormallyOverHeadIndicator=True, StakerUnitIndicator=True, StakerSpanAssemblyIndicator=True)
    
    

def CreateInitialMisc():
    print "Generating new site"
    site = Site.objects.create(domain='coopgisdev', name='coopgisdev')

def CreateInitialCOOPGISConfig():
    print "Generating new COOPGISConfig"
    New = COOPGISConfig()
    New.Name = 'DefaultBounds'
    New.Description = 'EPSG 4326 Default Bounts for Display, Format:  X1, Y1, X2, Y2'
    New.Value = '-106, 39.3, -105, 39.8'
    New.save()

    New = COOPGISConfig()
    New.Name = 'DefaultCenter'
    New.Description = 'EPSG 4326 Default Bounts for Display, Format:  X1, Y1'
    New.Value = '-105.302691, 39.536343'
    New.save()

    New = COOPGISConfig()
    New.Name = 'ShortDistanceUnit'
    New.Description = 'Unit for measuring short distances, such as the distance between nearby poles'
    New.Value = 'ft'
    New.save()

    New = COOPGISConfig()
    New.Name = 'LongDistanceUnit'
    New.Description = 'Unit for measuring short distances, such as the distance between substations'
    New.Value = 'mi'
    New.save()

    New = COOPGISConfig()
    New.Name = 'MinimumDistanceBetweenStations'
    New.Description = 'Distance searched when creating a new station for a potential matching station, using ShortDistanceUnit'
    New.Value = '0.25'
    New.save()


    New = COOPGISConfig()
    New.Name = 'MaximumDistanceToFindNearbyStations'
    New.Description = 'Maximum Distance searched when finding a nearby station, using ShortDistanceUnit'
    New.Value = '500'
    New.save()

    New = COOPGISConfig()
    New.Name = 'MaximumDistanceToFindNearbyRoads'
    New.Description = 'Maximum Distance searched when finding a road near a station, using ShortDistanceUnit'
    New.Value = '9000'
    New.save()
 



def CreateInitialAssemblies():
    print "Generating new stations, spans, and assemblies"
    Stations = []
    Spans = []

    Stations.append(Station.GetOrCreateClosestStation(InputPoint=Point(-105.3027, 39.53635, srid=4326)))
    New = Assembly.GetOrCreate(CompatibleUnit=CompatibleUnit.objects.filter(Name='7200 Transformer').get(), Quantity=1, Station=Stations[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=999)

    Stations.append(Station.GetOrCreateClosestStation(InputPoint=Point(-105.30275, 39.53630, srid=4326)))
    Spans.append(Span.GetOrCreate(StartStation=Stations[0], EndStation=Stations[-1]))
    New = Assembly.GetOrCreate(CompatibleUnit=CompatibleUnit.objects.filter(Name='Recloser').get(), Quantity=1, Station=Stations[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=101)
    New = Assembly.GetOrCreate(CompatibleUnit = CompatibleUnit.objects.filter(Name='Substation Bus').get(), Quantity=1, Span=Spans[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=999)

    Stations.append(Station.GetOrCreateClosestStation(InputPoint=Point(-105.30280, 39.53635, srid=4326)))
    Spans.append(Span.GetOrCreate(StartStation=Stations[0], EndStation=Stations[-1]))
    New = Assembly.GetOrCreate(CompatibleUnit=CompatibleUnit.objects.filter(Name='Recloser').get(), Quantity=1, Station=Stations[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=102)
    New = Assembly.GetOrCreate(CompatibleUnit = CompatibleUnit.objects.filter(Name='Substation Bus').get(), Quantity=1, Span=Spans[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=999)

    Stations.append(Station.GetOrCreateClosestStation(InputPoint=Point(-105.30285, 39.53640, srid=4326)))
    Spans.append(Span.GetOrCreate(StartStation=Stations[0], EndStation=Stations[-1]))
    New = Assembly.GetOrCreate(CompatibleUnit=CompatibleUnit.objects.filter(Name='Recloser').get(), Quantity=1, Station=Stations[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=103)
    New = Assembly.GetOrCreate(CompatibleUnit = CompatibleUnit.objects.filter(Name='Substation Bus').get(), Quantity=1, Span=Spans[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=999)

    Stations.append(Station.GetOrCreateClosestStation(InputPoint=Point(-105.30290, 39.53645, srid=4326)))
    Spans.append(Span.GetOrCreate(StartStation=Stations[0], EndStation=Stations[-1]))
    New = Assembly.GetOrCreate(CompatibleUnit=CompatibleUnit.objects.filter(Name='Recloser').get(), Quantity=1, Station=Stations[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=104)
    New = Assembly.GetOrCreate(CompatibleUnit = CompatibleUnit.objects.filter(Name='Substation Bus').get(), Quantity=1, Span=Spans[-1], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=999)



    #Start Circuit 101
    Stations.append(Station.GetOrCreateClosestStation(InputPoint=Point(-105.3028, 39.5361, srid=4326)))
    New = Assembly.GetOrCreate(CompatibleUnit=CompatibleUnit.objects.filter(Name='P50-3').get(), Quantity=1, Station=Stations[3], TagNumber = '1000', PhaseAIndicator=False, PhaseBIndicator=False, PhaseCIndicator=False, PhaseNeutralIndicator=False, PrimaryIndicator=True, CircuitNumber=101)
    Spans.append(Span.GetOrCreate(StartStation=Stations[1], EndStation=Stations[-1]))
    New = Assembly.GetOrCreate(CompatibleUnit = CompatibleUnit.objects.filter(Name='4 ACSR').get(), Quantity=1, Span=Spans[2], PhaseAIndicator=True, PhaseBIndicator=True, PhaseCIndicator=True, PhaseNeutralIndicator=True, PrimaryIndicator=True, CircuitNumber=101)

    Stations[-1].RebuildSymbology(EntireMap=False)

def ImportTestRoadData():
    #SELECT setval(pg_get_serial_sequence('"censusedge2013"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "censusedge2013";
    #SELECT setval(pg_get_serial_sequence('"coopgisroad"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "coopgisroad";
    CensusEdge.ImportShapeFiles(PathDjangoRoot + 'scripts/Install/Jefferson_CO_2013_CensusEdges/tl_2013_08059_edges.shp')
    CensusEdge.PopulateRoadsTable()


DeleteExisting()
ResetSequences()
LoadMapFiles()
CreateInitialMisc()
CreateInitialCOOPGISConfig()
CreateInstallStatuses()
CreateInitialCompatibleUnits()
CreateInitialAssemblies()

#ImportTestRoadData()




